<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设施编号" prop="facilityCode">
        <el-input v-model="queryParams.facilityCode" placeholder="请输入设施编号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="设施名称" prop="facilityName">
        <el-input v-model="queryParams.facilityName" placeholder="请输入设施名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="安放的厂房" prop="locationRoomCode">
        <el-input v-model="queryParams.locationRoomCode" placeholder="请输入安放的厂房" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['rooms:Facilities:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['rooms:Facilities:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['rooms:Facilities:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['rooms:Facilities:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="FacilitiesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设施编号" align="center" prop="facilityCode" />
      <el-table-column label="设施名称" align="center" prop="facilityName" />
      <el-table-column label="设施类型" align="center" prop="facilityType" />
      <el-table-column label="型号规格" align="center" prop="modelSpec" />
      <el-table-column label="生产厂家" align="center" prop="manufacturer" />
      <el-table-column label="安放的厂房" align="center" prop="locationRoomCode">
        <template slot-scope="scope">
          <!-- 加载中 -->
          <span v-if="scope.row.loadingRoomName" style="display: inline-block; min-width: 80px;">
            <el-skeleton active :rows="1" :columns="1" style="width: 100%;"></el-skeleton>
          </span>
          <!-- 已加载名称 -->
          <span v-else-if="scope.row.roomName" style="display: inline-block; min-width: 80px;">
            {{ scope.row.roomName }}
          </span>
          <!-- 编码兜底 -->
          <span v-else-if="scope.row.locationRoomCode" style="display: inline-block; min-width: 80px;">
            {{ scope.row.locationRoomCode }}
          </span>
          <!-- 无数据 -->
          <span v-else style="display: inline-block; min-width: 80px;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['rooms:Facilities:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['rooms:Facilities:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="设施名称" prop="facilityName">
          <el-input v-model="form.facilityName" placeholder="请输入设施名称" />
        </el-form-item>
        <el-form-item label="型号规格" prop="modelSpec">
          <el-input v-model="form.modelSpec" placeholder="请输入型号规格" />
        </el-form-item>

        <el-form-item label="设施类型" prop="facilityType">
          <!-- 使用输入框接收字符串类型的设施类型 -->
          <el-input v-model="form.facilityType" placeholder="请输入设施类型" type="text">
          </el-input>
        </el-form-item>
        <el-form-item label="生产厂家" prop="manufacturer">
          <el-input v-model="form.manufacturer" placeholder="请输入生产厂家" />
        </el-form-item>
        <!-- 所属厂房下拉 -->
        <el-form-item label="所属厂房" prop="roomCode">
          <el-select v-model="form.roomCode" placeholder="请选择所属厂房" clearable :disabled="form.id">
            <el-option v-for="room in roomOptions" :key="room.value" :label="room.label" :value="room.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFacilities, getFacilities, delFacilities, addFacilitiesByRoomCode, updateFacilities } from "@/api/rooms/Facilities"
import { listRoomsinformation, getRoomNameByRoomCode } from "@/api/rooms/roomsinformation"

export default {
  name: "Facilities",
  data() {
    return {
      loading: true,          // 表格加载
      ids: [],                // 选中ID
      single: true,           // 单条禁用
      multiple: true,         // 多条禁用
      showSearch: true,       // 显示搜索
      total: 0,               // 总条数
      FacilitiesList: [],     // 表格数据
      title: "",              // 弹窗标题
      open: false,            // 弹窗显隐
      queryParams: {          // 查询参数
        pageNum: 1,
        pageSize: 10,
        facilityCode: null,
        facilityName: null,
        locationRoomCode: null,
      },
      form: {                 // 弹窗表单
        id: null,
        facilityCode: null,
        facilityName: null,
        facilityType: null,
        modelSpec: null,
        manufacturer: null,
        locationRoomCode: null,
        createdAt: null,
        isDelete: null,
        roomCode: null,       // 绑定下拉的编码
      },
      rules: {                // 表单校验
        facilityName: [
          { required: true, message: '请输入设施名称', trigger: 'blur' }
        ],
      },
      roomOptions: [],        // 厂房下拉数据源
      roomNameCache: {},      // 厂房名称缓存
    }
  },
  created() {
    this.getList();          // 加载表格数据
    this.getRoomList();      // 加载厂房下拉数据
  },
  methods: {
    // 获取设施列表
    getList() {
      this.loading = true;
      listFacilities(this.queryParams).then(res => {
        // 初始化表格数据，添加响应式字段
        this.FacilitiesList = res.rows.map(row => ({
          ...row,
          roomName: '',
          loadingRoomName: false
        }));
        this.total = res.total;

        // 批量查询厂房名称
        this.FacilitiesList.forEach(row => {
          if (row.locationRoomCode) this.fetchRoomName(row);
        });

        this.loading = false;
      }).catch(err => {
        this.loading = false;
        this.$modal.msgError('获取设施列表失败');
      });
    },

    // 获取厂房下拉数据
    getRoomList() {
      listRoomsinformation({}).then(res => {
        this.roomOptions = res.rows.map(room => ({
          label: room.roomName,
          value: room.roomCode
        }));
        if (!this.roomOptions.length) {
          this.$modal.msgWarning('暂无厂房数据，请先添加');
        }
      }).catch(err => {
        this.$modal.msgError('加载厂房列表失败');
      });
    },

    // 查询单个厂房名称（带缓存）
    fetchRoomName(row) {
      if (!row.locationRoomCode) return;
      if (this.roomNameCache[row.locationRoomCode]) {
        this.$set(row, 'roomName', this.roomNameCache[row.locationRoomCode]);
        return;
      }
      row.loadingRoomName = true;
      getRoomNameByRoomCode(row.locationRoomCode).then(res => {
        if (res.data?.roomName) {
          this.roomNameCache[row.locationRoomCode] = res.data.roomName;
          this.$set(row, 'roomName', res.data.roomName);
        }
      }).catch(err => {
        this.$modal.msgError('获取厂房名称失败');
      }).finally(() => {
        row.loadingRoomName = false;
      });
    },

    // 取消弹窗
    cancel() {
      this.open = false;
      this.resetForm('form');
    },

    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 重置搜索
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },

    // 表格多选
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    // 新增
    handleAdd() {
      this.resetForm('form'); // 先重置表单绑定的字段（如facilityName等）
      // 关键：手动重置form为初始空对象，清除所有缓存属性（id、locationRoomCode等）
      this.form = {
        id: null,
        facilityCode: null,
        facilityName: null,
        facilityType: null,
        modelSpec: null,
        manufacturer: null,
        locationRoomCode: null, // 清除修改时残留的厂房编码
        createdAt: null,        // 清除修改时残留的创建时间
        isDelete: null,
        roomCode: null,         // 清除修改时残留的下拉选中值
        roomName: null          // 清除修改时残留的厂房名称
      };
      this.open = true;
      this.title = "添加设施管理";
    },

    // 修改
    handleUpdate(row) {
      this.resetForm('form');
      const id = row ? row.id : (this.ids[0] || null);
      if (!id) return this.$modal.msgError('请选择一条记录');

      getFacilities(id).then(res => {
        this.form = { ...res.data };
        // 回显厂房名称（从缓存或接口）
        if (this.form.locationRoomCode) {
          this.form.roomCode = this.form.locationRoomCode; // 绑定编码
          if (this.roomNameCache[this.form.locationRoomCode]) {
            this.form.roomName = this.roomNameCache[this.form.locationRoomCode];
          } else {
            this.fetchRoomName({
              locationRoomCode: this.form.locationRoomCode,
              loadingRoomName: false,
              roomName: ''
            }).then(() => {
              this.form.roomName = this.roomNameCache[this.form.locationRoomCode];
            });
          }
        }
        this.open = true;
        this.title = "修改设施管理";
      }).catch(err => {
        this.$modal.msgError('获取详情失败');
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理表单数据
          const formData = { ...this.form };

          if (formData.id != null) {
            // 修改操作（保持不变）
            updateFacilities(formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error('修改失败', error);
              this.$modal.msgError('修改失败，请重试');
            });
          } else {
            // 新增操作：关键修正！使用 form.roomCode 作为参数
            if (!formData.roomCode) { // 校验下拉是否选择
              this.$modal.msgError("请选择所属厂房");
              return;
            }

            // 调用接口时，传递 form.roomCode 作为 roomCode 参数
            addFacilitiesByRoomCode(formData, formData.roomCode).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error('新增失败', error);
              this.$modal.msgError('新增失败，请重试');
            });
          }
        }
      });
    },

    // 删除
    handleDelete(row) {
      const ids = row ? [row.id] : this.ids;
      if (!ids.length) return this.$modal.msgError('请选择记录');

      this.$modal.confirm('确认删除选中数据？').then(() => {
        delFacilities(ids).then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
          this.ids = [];
          this.single = true;
          this.multiple = true;
        }).catch(err => {
          this.$modal.msgError('删除失败');
        });
      });
    },

    // 导出
    handleExport() {
      this.download('rooms/Facilities/export', { ...this.queryParams }, `Facilities_${new Date().getTime()}.xlsx`)
        .catch(err => this.$modal.msgError('导出失败'));
    }
  }
}
</script>